from django_redis import get_redis_connection
import json
import datetime



def get_coupons(user_id):
    user_id = user_id
    redis = get_redis_connection('coupon')
    coupon_list = redis.keys(f"{user_id}:*")
    coupon_id_list = [i.decode() for i in list(coupon_list)]
    coupon_data = []
    for coupon_key in coupon_id_list:
        coupon_item = {"user_coupon_id":int(coupon_key.split(':')[-1])}
        coupon_hash = redis.hgetall(coupon_key)
        for key, value in coupon_hash.items():
            key = key.decode()
            value = value.decode()
            if key == "cd_department":
                value = json.loads(value)
            coupon_item[key] = value
        coupon_data.append(coupon_item)
    return coupon_data




def get_enable_coupons(user_id,department,amount):
    coupons = get_coupons(user_id)
    enable_coupons = []
    for coupon in coupons:
        if ((department in [i["department__id"] for i in coupon["cd_department"]] or coupon['coupon_type'] == "0")
                and coupon['use_status'] == '0' and datetime.datetime.strptime(coupon['end_time'],'%Y-%m-%d %H:%M:%S')
                > datetime.datetime.now()):
            if int(coupon['condition']) <= amount:
                enable_coupons.append(coupon)
    return enable_coupons










